<script setup lang='ts'>
import { nextTick, onMounted, onUpdated, ref } from "vue"
import { getBookContent, getBookChapterList, getPublishBookChapterList, getBookDetail, getBookComment } from "@/api/index"
import { useRouter } from 'vue-router'
import LoadingPage from "@/components/LoadingPage.vue"
import { useCounterStore } from '../stores/counter'
import { showFailToast, showSuccessToast, showToast, showConfirmDialog } from 'vant';
import LoadingView from "@/components/LoadingView.vue"
const store = useCounterStore()
const isLoadingPage = ref<boolean>(true)
const isLoadingView = ref<boolean>(false)
const $router = useRouter()
const content = ref<any>([])
const loading = ref<boolean>(false)
const finished = ref<boolean>(false)
const isLoading = ref<boolean>(false)
const current_num = ref<any>(0)
const currentBooks = ref<any>(JSON.parse(`${localStorage.getItem('books')}`) || [])
//书籍信息
const bookDetail = ref<any>()

const reverseChapterList = ref<any>([])

const bookChapterList = ref<any>([])
const bookComment = ref<any>()
let readArr = [Number($router.currentRoute.value.query.index)]

onMounted(async () => {

    let currentBook = currentBooks.value.filter((o: any) => o.source_uuid == $router.currentRoute.value.query.source_uuid)
    //如果此书籍添加在书架，就替换已读数组
    if (currentBook.length) {
        readArr = currentBook[0]?.read
    }

    let res = await getBookContent($router.currentRoute.value.query.source_uuid, $router.currentRoute.value.query.content_uuid);

    content.value = [res.data.data]
    current_num.value = $router.currentRoute.value.query.index

    let querys = $router.currentRoute.value.query

    let bookChapterRes = await getBookChapterList(querys.source_uuid)
    if (bookChapterRes.data.code == -1) {
        let bookPubliskCahpterRes = await getPublishBookChapterList(querys.source_uuid)
        bookChapterList.value = bookPubliskCahpterRes.data.ncx.navMap.navPoint
        bookChapterList.value.forEach((o: any) => {
            if (o.navPoint?.length > 0) {

                reverseChapterList.value = [...reverseChapterList.value, o]
                reverseChapterList.value = [...reverseChapterList.value, ...o.navPoint]

            } else {
                reverseChapterList.value = [...reverseChapterList.value, o]
            }

        })
    } else {
        bookChapterList.value = bookChapterRes.data.data.catalog
        reverseChapterList.value = bookChapterList.value
    }
    store.getChapter(reverseChapterList.value)

    let bookDetailRes = await getBookDetail(querys.source_uuid, querys.title)
    bookDetail.value = bookDetailRes.data.feed.entry

    let bookCommentRes = await getBookComment(querys.source_uuid)
    bookComment.value = bookCommentRes.data.all
    if (currentBooks.value.find((o: any) => o.source_uuid == $router.currentRoute.value.query.source_uuid)) {
        isInBookShelf.value = true
    }
    isLoadingPage.value = false

})

const changeLocalBookChapter = () => {
    let a = currentBooks.value.findIndex((o: any) => o.source_uuid == $router.currentRoute.value.query.source_uuid)

    if (a != -1) {
        currentBooks.value[a].currentChapter = current_num.value + 1;
        currentBooks.value[a].content_uuid = store.bookChapterList[current_num.value].uuid

        localStorage.setItem('books', JSON.stringify([...currentBooks.value]))
    }
}

const onLoad = async () => {
    if (!isLoading.value) {
        isLoading.value = true;

        if (!(bookChapterList.value[current_num.value + 1]?.needPay || bookChapterList.value[current_num.value + 1]?.vip == 1)) {
            current_num.value = Number(current_num.value) + 1
        } else {
            // showFailToast('付费内容，请登录购买！')
            needPay.value = true
            finished.value = true;
            return

        }
        let res = await getBookContent($router.currentRoute.value.query.source_uuid, store.bookChapterList[current_num.value]?.uuid);
        content.value = [...content.value, res.data.data]

        loading.value = false
        isLoading.value = false

        if (content.value.length >= store.bookChapterList.length) {
            finished.value = true;
        }
        readArr.push(current_num.value)
        updateRouter();
        changeLocalBookChapter()
    }
}
const isShowMenuTop = ref<boolean>(false)
const isShowMenuBottom = ref<boolean>(false)
const isShowChapterList = ref<boolean>(false)
const isShowMore = ref<boolean>(false)

const showMenu = () => {
    isShowMenuTop.value = true
    isShowMenuBottom.value = true
}

//更新路由函数（使在读章节变化，可用于分享）
const updateRouter = () => {
    let querys = $router.currentRoute.value.query
    $router.replace({ path: '/content', query: { source_uuid: querys.source_uuid, content_uuid: store.bookChapterList[current_num.value].uuid, title: querys.title, index: current_num.value } })
}
const toContentPage = async (item: any, index: number) => {

    if (bookChapterList.value[index]?.needPay || bookChapterList.value[index]?.vip == 1) {
        needPay.value = true
        isShowChapterList.value = false
    } else {
        needPay.value = false
        isLoadingView.value = true
        read.value.scrollTop = 0
        let res = await getBookContent($router.currentRoute.value.query.source_uuid, store.bookChapterList[index].uuid);

        content.value = [res.data.data]
        current_num.value = index
        readArr.push(current_num.value)
        //更新路由
        updateRouter();
        //更新本地书籍章节（如果该书籍保存在本地）
        changeLocalBookChapter()

        isLoadingView.value = false
        isShowChapterList.value = false
        isShowMenuBottom.value = false
    }
}

const prevOrNext = async (str: string) => {
    isLoadingView.value = true
    if (str == 'prev') {
        current_num.value = Number(current_num.value) - 1;
        if (!store.bookChapterList[current_num.value].needPay) {
            needPay.value = false
        }
        if (current_num.value >= 0) {
            var res = await getBookContent($router.currentRoute.value.query.source_uuid, store.bookChapterList[current_num.value].uuid);
        } else {
            current_num.value = 0
            showFailToast('没有上一章了！')
            isLoadingView.value = false
        }
    } else {  //下一章

        current_num.value = Number(current_num.value) + 1;

        if (store.bookChapterList[current_num.value].needPay) {
            //如果下一章需要购买，就不需要请求数据了
            needPay.value = true
            current_num.value = Number(current_num.value) - 1;

        } else {
            var res = await getBookContent($router.currentRoute.value.query.source_uuid, store.bookChapterList[current_num.value].uuid);
        }

    }
    if (res && res.data.code != -1) {
        content.value = [res.data.data]
        read.value.scrollTop = 0
    }

    //导入已读章节编号
    readArr.push(current_num.value)
    //更新路由
    updateRouter()
    isLoadingView.value = false
    changeLocalBookChapter()
    isShowMenuBottom.value = false
    window.scrollTo(0, 0);
}

const isday = ref<any>(true)
const checked = ref<boolean>(false)

const read = ref<any>()
const addBookToShelf = () => {

    let obj = {
        content_uuid: store.bookChapterList[current_num.value].uuid,
        source_uuid: $router.currentRoute.value.query.source_uuid,
        cover: bookDetail.value.link[1].href,
        currentChapter: current_num.value,
        title: $router.currentRoute.value.query.title,
        read: [...readArr]
    }
    currentBooks.value = [obj, ...currentBooks.value]
    localStorage.setItem('books', JSON.stringify(currentBooks.value))

    if (currentBooks.value.find((o: any) => o.source_uuid == $router.currentRoute.value.query.source_uuid)) {
        isInBookShelf.value = true
    }
    showSuccessToast('加入书架成功')

}
const isInBookShelf = ref<boolean>(false)

const needPay = ref<boolean>(false)
//点击目录
const clickChapterMenu = () => {
    isShowChapterList.value = true;
    isShowMenuBottom.value = false
    nextTick(() => {
        ulist.value.scrollTop = 43.4 * Number($router.currentRoute.value.query.index)
    })

}
const ulist = ref<any>(null)

const buyBookChapter = () => {
    if (store.userInfo) {
        showConfirmDialog({
            title: '购买',
            message:
                `确认购买${store.bookChapterList[current_num.value + 1].title}?`,
        })
            .then(() => {
                showSuccessToast('购买成功！')
            })
            .catch(() => {
                showFailToast('取消购买！')
            });
    } else {
        showFailToast('请登录！');
        setTimeout(() => {
            $router.push({ path: '/login', query: $router.currentRoute.value.query })
        }, 1000)
    }
}

const buyBookChapterMore = () => {
    if (store.userInfo) {
        $router.push({ path: '/buy', query: { tocId: $router.currentRoute.value.query.source_uuid } })
    } else {
        showFailToast('请登录！');
        setTimeout(() => {
            $router.push({ path: '/login', query: $router.currentRoute.value.query })
        }, 1000)
    }

}
</script>

<template>
    <div>
        <Transition name="content">
            <div>
                <LoadingView v-if="isLoadingView" />
                <LoadingPage v-if="isLoadingPage" />
                <div class="b-content" v-if="content" :class="{ night: !isday }" ref="read">

                    <div class="title-copy" v-if="isShowMenuBottom">
                        <img src="@/assets/imgs/返回1.png" alt="" @click="$router.back()">
                        <div class="right">
                            <img src="@/assets/imgs/消息.png" alt=""
                                @click="$router.push({ path: '/all-comment', query: { source_uuid: $router.currentRoute.value.query.source_uuid, url: bookComment.next } })">

                            <img src="@/assets/imgs/标签2.png" alt="">
                        </div>
                    </div>
                    <div class="add-book" v-if="isShowMenuBottom && !isInBookShelf" @click="addBookToShelf">
                        <img src="@/assets/imgs/加1.png" alt="">
                        <span>加入书架</span>
                    </div>

                    <div class="book-content-container">

                        <van-list v-model:loading="loading" :finished="finished" :offset="1" finished-text="没有更多了"
                            loading-text="数据加载中" error-text="加载失败" @load="onLoad" v-if="!isLoadingPage && !needPay">
                            <ul class="list" @click.stop="showMenu">
                                <li v-for="chapter, index in content" :key="index">
                                    <div v-html="chapter?.content"></div>
                                </li>
                            </ul>
                        </van-list>

                        <div class="need-buy" v-else @click="isShowMenuBottom = true">
                            <p>{{ store.bookChapterList ? store.bookChapterList[current_num + 1]?.title : '' }}</p>
                            <p>欢迎观看网易云阅读！</p>
                            <div class="price">
                                价格：<span>{{
                                    store.bookChapterList ? store.bookChapterList[current_num + 1]?.price
                                    : 0
                                }}阅点</span>
                            </div>
                            <div class="balance">
                                余额：<span>...阅点</span>
                            </div>
                            <button @click.stop="buyBookChapter">购买</button>
                            <div class="buy-more" @click.stop="buyBookChapterMore">
                                <span>购买多章</span>
                                <img src="@/assets/imgs/右箭头.png" alt="">
                            </div>
                        </div>

                        <van-popup v-model:show="isShowMenuBottom" position="bottom" :style="{ height: '25%' }" class="menu"
                            :overlay-style="{ backgroundColor: 'rgba(255,255,255,0.1)' }">
                            <div class="menu-title">
                                <span>{{ store.bookChapterList[current_num]?.title }}</span>
                            </div>
                            <div class="prevOrNext">
                                <div class="left" @click="prevOrNext('prev')">
                                    <img src="@/assets/imgs/返回1.png" alt="">
                                    <span>上一章</span>
                                </div>
                                <div class="right" @click="prevOrNext('next')">
                                    <span>下一章</span>
                                    <img src="@/assets/imgs/右箭头.png" alt="">
                                </div>
                            </div>
                            <div class="menu-action">
                                <ul class="list">
                                    <li @click="clickChapterMenu">
                                        <img src="@/assets/imgs/列表3.png" alt="">
                                        <span>目录</span>
                                    </li>
                                    <li>
                                        <img src="@/assets/imgs/Aa1.png" alt="">
                                        <span>设置</span>
                                    </li>
                                    <li>
                                        <img src="@/assets/imgs/月亮1.png" alt="" @click="isday = false" v-if="isday">
                                        <span v-if="isday">夜间</span>
                                        <img src="@/assets/imgs/日间模式.png" alt="" @click="isday = true" v-if="!isday">
                                        <span v-if="!isday">日间</span>
                                    </li>
                                    <li @click="isShowMore = true; isShowMenuBottom = false">
                                        <img src="@/assets/imgs/更多1.png" alt="">
                                        <span>更多</span>
                                    </li>
                                </ul>
                            </div>
                        </van-popup>

                        <van-popup v-model:show="isShowChapterList" position="left" :style="{ width: '80%' }"
                            :overlay-style="{ backgroundColor: 'rgba(255,255,255,0.1)' }" duration="0.1">
                            <div class="chapter">
                                <div class="chapter-title">
                                    <img src="@/assets/imgs/返回1.png" alt="" @click="$router.back()">
                                    <span>目录</span>
                                    <span></span>
                                </div>
                                <div class="xx">
                                    <LoadingPage v-if="isLoadingPage" />
                                    <div class="yy" v-else>
                                        <div class="author-msg">
                                            <div class="img">
                                                <img :src="`${bookDetail.link[1].href}?imageView&thumbnail=240y336`" alt="">
                                            </div>
                                            <div class="msg">
                                                <span>{{ $router.currentRoute.value.query.title }}</span>
                                                <span>{{ bookDetail.author.name }}</span>
                                            </div>
                                        </div>
                                        <div class="chapter-list">
                                            <div class="all-reverse">
                                                <span>共{{ reverseChapterList.length }}章</span>
                                            </div>
                                            <div class="lists" ref="ulist">
                                                <ul class="list">
                                                    <li v-for="item, index in reverseChapterList" :key="index"
                                                        @click="toContentPage(item, index)">
                                                        <span
                                                            :class="{ c: current_num == index, read: readArr?.includes(Number(index)) && current_num != index }">{{
                                                                item.title || item.navLabel?.slice(1, item.navLabel.length)
                                                            }}</span>
                                                        <img src="@/assets/imgs/锁2.png" alt=""
                                                            v-if="item.needPay || item.vip == 1">
                                                    </li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </van-popup>
                        <van-popup v-model:show="isShowMore" position="bottom" :style="{ height: '40%' }" class="more">
                            <ul class="list">
                                <li>
                                    <span>分享书籍</span>
                                    <img src="@/assets/imgs/右箭头.png" alt="">
                                </li>
                                <li>
                                    <span>搜索</span>
                                    <img src="@/assets/imgs/右箭头.png" alt="">
                                </li>
                                <li>
                                    <span>下载全部可读章节</span>
                                    <img src="@/assets/imgs/右箭头.png" alt="">
                                </li>
                                <li>
                                    <span>点击两侧均翻到下一页</span>
                                    <van-checkbox v-model="checked" shape="square"></van-checkbox>
                                </li>
                                <li>
                                    <span>护眼模式</span>
                                    <van-button type="default" round>秒速安装</van-button>
                                </li>
                            </ul>
                        </van-popup>
                    </div>

                </div>
            </div>
        </Transition>
    </div>
</template>

<style lang="less">
.content-leave-active {
    transition: all 0.2s;
}

.content-leave-from {
    transform: translateY(0);
}

.content-leave-to {
    transform: translateY(-100vh);
}


.b-content {
    position: relative;
    padding: 10rem;
    width: 100vw;
    height: 100vh;
    overflow: auto;
    background-color: rgb(247, 245, 247);
    // background-color: #fff;

    .book-content-container {


        .need-buy {
            width: 100%;
            height: 100%;
            padding: 20rem;

            p {
                font-size: 16rem;
                color: #333;
                margin-bottom: 10rem;
            }

            .price {
                font-size: 14rem;
                color: #666;

                span {
                    color: #fc1c1c;
                    font-size: 14rem;
                }
            }

            .balance {
                font-size: 14rem;
                color: #666;

                span {
                    color: #666;
                }

            }

            button {
                width: 80%;
                height: 40rem;
                border-radius: 20rem;
                background-color: #fc1c1c;
                color: #fff;
                border: none;
                margin-left: 10%;
                margin-top: 40rem;
            }

            .buy-more {
                display: flex;
                align-items: center;
                justify-content: center;
                margin-top: 10rem;

                span {
                    color: #888;
                }

                img {
                    width: 18rem;
                }
            }

        }
    }

    &.night {
        background-color: #2d2d2d;
        color: #888;

        h1,
        h2,
        h3,
        h4,
        h5,
        h6 {
            color: #888;

            span {
                color: #888 !important;
            }
        }

        span {
            color: #888;
        }
    }

    .title {
        display: flex;
        justify-content: space-between;
        align-items: center;

        img {
            width: 25rem;
        }

        span {
            font-size: 17rem;
            // color: #333;
        }
    }

    .title-copy {
        position: fixed;
        left: 0;
        top: 0;
        height: 50rem;
        width: 100vw;
        background-color: #fff;
        z-index: 9999;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 15rem 0 10rem;

        img {
            width: 30rem;
            height: 30rem;
        }

        .right {
            display: flex;

            img {
                width: 25rem;
                height: 25rem;

                &:last-child {
                    margin-left: 20rem;
                }
            }
        }
    }

    .add-book {
        position: fixed;
        right: 0;
        top: 100rem;
        background-color: #bb1515;
        display: flex;
        align-items: flex-start;
        color: #fff;
        padding: 5rem;
        z-index: 9999;

        img {
            width: 20rem;
            font-size: 0;
        }

        span {
            color: #fff;
            font-size: 13rem;
        }
    }


    ul.list {

        li {
            .m-content {
                text-indent: 2em;


                >h1 {
                    text-align: center;
                    margin-top: 30rem;

                    span {
                        font-size: 17rem;
                        color: #333;
                        font-weight: bold;
                    }

                    margin-bottom: 20rem;
                }

                p {
                    line-height: 2em;
                    margin-bottom: 20rem;
                }

                img {
                    width: 100%;
                }

            }
        }
    }

    .menu {
        padding: 20rem 20rem 0;

        .menu-title {
            text-align: center;
            margin-bottom: 20rem;

            span {
                font-size: 14rem;
                color: #2d2d2d;
            }
        }

        .prevOrNext {
            display: flex;
            justify-content: space-between;

            span {
                font-size: 15rem;
                color: #333;
            }

            .left {
                display: flex;
                align-items: center;

                img {
                    width: 20rem;
                }
            }

            .right {
                display: flex;
                align-items: center;

                img {
                    width: 20rem;
                }
            }
        }

        .menu-action {
            margin-top: 20rem;

            ul.list {
                display: flex;
                justify-content: space-between;

                li {
                    img {
                        width: 25rem;
                    }

                    span {
                        color: #2d2d2d;
                    }
                }
            }
        }
    }

    .more {
        ul.list {
            li {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 12rem 10rem;
                border-bottom: 1px solid #eee;

                &:last-child {
                    border-bottom: none;
                }

                span {
                    font-size: 14rem;
                }

                img {
                    width: 20rem;
                }
            }
        }
    }
}

.chapter {
    padding-top: 15rem;
    height: 100vh;

    .chapter-title {
        padding: 0 10rem 15rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #eee;

        img {
            width: 25rem;
            height: 25rem;
        }

        span {
            color: #333;
            font-size: 17rem
        }
    }

    .xx {
        width: 100%;
        height: calc(100vh - 58rem);

        .yy {
            .author-msg {
                padding: 20rem 10rem;
                display: flex;
                justify-content: left;
                align-items: center;

                .img {
                    margin-right: 20rem;

                    img {
                        width: 70rem;
                        height: 98rem;
                        box-shadow: 0 0 5rem 1rem #ccc;
                    }
                }

                .msg {
                    display: flex;
                    flex-direction: column;

                    span {
                        &:first-child {
                            font-size: 16rem;
                            color: #333;
                            margin-bottom: 10rem;
                        }
                    }
                }
            }

            .chapter-list {
                padding: 0 10rem;

                .all-reverse {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;

                    >span {
                        font-size: 15rem;
                        color: #333;
                    }

                    .reverse {
                        display: flex;
                        align-items: center;
                        padding: 0 6rem;
                        border: 1rem solid #ccc;
                        border-radius: 20rem;

                        span {
                            font-size: 14rem;
                            margin-right: 3rem;
                        }

                        img {
                            width: 10rem;

                        }
                    }
                }

                .lists {
                    height: 435rem;
                    overflow: auto;

                    ul.list {
                        margin-top: 10rem;

                        li {
                            padding: 10rem 0;
                            border-bottom: 1px dotted #eee;
                            display: flex;
                            justify-content: space-between;
                            align-items: center;

                            &:last-child {
                                border-bottom: none;
                            }

                            span {
                                font-size: 14rem;
                                color: #666;

                                &.c {
                                    color: #fc1c1c;
                                }

                                &.read {
                                    color: #ccc;
                                }
                            }

                            img {
                                width: 20rem;
                            }
                        }
                    }
                }
            }
        }
    }

}
</style>
